<?php

namespace App\Repositories\RBAC;

use App\Models\RBAC\Permission;
use App\Repositories\BaseRepositoryEloquent;

/**
 * Class PermissionRepositoryEloquent.
 *
 * @package namespace App\Repositories;
 */
class PermissionRepositoryEloquent extends BaseRepositoryEloquent implements PermissionRepository
{
    /**
     * @var array
     */
    protected $fieldSortable = [
        'position' => 'desc',
        'id' => 'asc'
    ];

    /**
     * @var array
     */
    protected $fieldSearchable = [
        'name' => "like",
        'display_name' => "like",
        'is_menu',
    ];

    /**
     * Specify Model class name
     *
     * @return string
     */
    public function model()
    {
        return Permission::class;
    }

    /**
     * 获取父级菜单 两级
     * User: Zhangxy
     * Date: 2018-08-15
     * @return mixed
     */
    public function getParentMenus()
    {

        $rootMenuIds = [];
        $rootMenus = $this->rootMenus();
        if (!is_empty($rootMenus)) {
            $rootMenuIds = array_keys($rootMenus->toArray());
        }

        $navigationList = [];

        $navigation = $this->skipCriteria()->scopeQuery(function ($query) {
            return $query->orderBy('position', 'desc')->orderBy('id', "asc");
        })->all();

        if (!is_empty($navigation)) {
            $rootNavigation = [];
            foreach ($rootMenuIds as $index => $rootMenuId) {
                $rootNavigation[$rootMenuId] = null;
            }
            foreach ($navigation as $index => $item) {
                if (empty($item->pid)) {
                    $rootNavigation[$item->id]['self'] = $item->attributesToArray();
                } elseif (in_array($item->pid, $rootMenuIds)) {
                    $rootNavigation[$item->pid]['subMenus'][] = $item->attributesToArray();
                }
            }

            foreach ($rootNavigation as $index => $item) {
                if (isset($item['self'])) {
                    $navigationList[$item['self']['id']] = $item['self'];
                }
                if (isset($item['subMenus'])) {
                    foreach ($item['subMenus'] as $subIndex => $subItem) {
                        $subItem['display_name'] = "---- " . $subItem['display_name'];
                        $navigationList[$subItem['id']] = $subItem;

                    }
                }
            }
        }

        return $navigationList;

    }

    /**
     * 获取 根 菜单
     * User: Zhangxy
     * Date: 2018-08-15
     * @return mixed
     */
    public function rootMenus()
    {
        return $this->model->isRoot()->isMenu()->orderBy('position', 'desc')->orderBy("id", "asc")->get()->keyBy('id');
    }

    /**
     * 根据路由名称得到 导航信息
     * todo Zhangxy 优化考虑加入缓存
     * @param $route_name
     * User: Zhangxy
     * Date: 2018-08-15
     * @return array
     */
    public function getBreadcrumbs($route_name)
    {
        $permission = $this->model->with("parentPermission")->where('name', $route_name)->orderBy('id',
            'asc')->first();

        $permissionArray = $this->convert2Array($permission);

        if (!is_empty($permissionArray)) {
            foreach ($permissionArray as $index => &$item) {

                // 一级菜单的 链接 获取它下边的第一个菜单的链接
                if (empty($item->pid)) {
                    $firstPermission = $this->model
                        ->isMenu()
                        ->where('root_id', $item->id)
                        ->orderBy('position', 'desc')
                        ->orderBy('id', 'asc')
                        ->first();
                    if (!is_empty($firstPermission)) {
                        $firstPermission->display_name = $item->display_name;
                        $item = $firstPermission;
                    }
                }
            }
        }

        return $permissionArray;
    }

    /**
     * 将层级结构的权限项 转换成 平级的数组
     * @param $permission
     * User: Zhangxy
     * Date: 2018-08-26
     * @return array
     */
    protected function convert2Array($permission)
    {
        $permissionNameList = [];
        if (!is_empty($permission)) {
            if ($permission->pid > 0) {
                $parentPermission = $permission->parentPermission;
                if (!is_empty($parentPermission)) {
                    $permissionNameList = array_merge($permissionNameList,
                        $this->convert2Array($parentPermission));
                }
            }
            $permissionNameList[$permission->name] = $permission;
        }
        return $permissionNameList;
    }

    /**
     * 获取权限名称列表
     * @param $permission
     * User: Zhangxy
     * Date: 2018-08-20
     * @return array
     */
    public function getPermissionNameList($permission)
    {
        $permissionNameList = [];
        if (!is_empty($permission)) {
            foreach ($permission as $index => $item) {
                $permissionNameList[$item->name] = $item->is_menu;
                if (!is_empty($item->subPermissions)) {
                    $permissionNameList = array_merge($permissionNameList,
                        $this->getPermissionNameList($item->subPermissions));
                }
            }
        }
        return $permissionNameList;
    }

}
